package com.wz.spider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.wz.util.KeyBoard;
import com.wz.util.StringUtil;

public class NewHttpClientUtil {
	private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();
    private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class);
    public  static CookieStore cookieStore = new BasicCookieStore();
    public  static CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())  
            .setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig)  
            .setDefaultCookieStore(cookieStore).build();
    public  static HttpClientContext context = HttpClientContext.create();

	/** 
     * 发送Get请求Https
     * @param httpPost
     * @return
	 * @throws IOException
     */  
	private static String sendHttpsGet(String url) throws IOException {
		HttpEntity entity = null;
		CloseableHttpResponse  response = httpClient.execute(new HttpGet(url), context);
		try {
			cookieStore = context.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            for (Cookie cookie : cookies) {
                System.out.println("key:" + cookie.getName() + "  value:" + cookie.getValue());
            }
			// 执行请求
			entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally{
			response.close();
		}
	}

	public static String post(String url, String parameters)  
            throws ClientProtocolException, IOException {
		HttpEntity entity = null;
        HttpPost httpPost = new HttpPost(url);  
        List<NameValuePair> nvps = toNameValuePairList(parameters);  
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));  
        CloseableHttpResponse response = httpClient.execute(httpPost, context);  
        try {  
            cookieStore = context.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();  
            for (Cookie cookie : cookies) {  
                LOG.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());  
            }
            entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
        } finally {
            response.close();
        }
    }

	@SuppressWarnings("unused")  
    private static List<NameValuePair> toNameValuePairList(String parameters) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        String[] paramList = parameters.split("&");
        for (String parm : paramList) {
            int index = -1;
            for (int i = 0; i < parm.length(); i++) {
                index = parm.indexOf("=");
                break;
            }
            String key = parm.substring(0, index);
            String value = parm.substring(++index, parm.length());
            nvps.add(new BasicNameValuePair(key, value));
        }
        System.out.println(nvps.toString());
        return nvps;
    }

    //下载验证码图片
    public static void downLoadPic(String url) throws IOException{
    	String destfilename = "D:\\GitRes\\Trailplant\\trialplant-proj\\trialplant-core\\temp\\temp.jpg";

    	HttpGet httpget = new HttpGet(url);

    	File file = new File(destfilename);
    	if (file.exists()) {
    		file.delete();
    	}

    	CloseableHttpResponse response = httpClient.execute(httpget, context);
    	HttpEntity entity = response.getEntity();
		InputStream in = entity.getContent();
		FileOutputStream fout = null;
    	try {
    		cookieStore = context.getCookieStore();  
            List<Cookie> cookies = cookieStore.getCookies();  
            for (Cookie cookie : cookies) {  
                System.out.println("key:" + cookie.getName() + "  value:" + cookie.getValue());  
            }
    		
    		fout = new FileOutputStream(file);
    		int l = -1;
    		byte[] tmp = new byte[2048];
    		while ((l = in.read(tmp)) != -1) {
    			fout.write(tmp);
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally{
    		response.close();
    		fout.close();
    		in.close();
    	}
    	httpget.releaseConnection();
    }
   
    public static void main(String[] args) throws ClientProtocolException, IOException {
    	try {
    		downLoadPic("http://i.baimao.com/user/center/getCaptcha?r=" + Math.random());
    	} catch (IOException e) {
    	}

    	String captcha = KeyBoard.keyIn();

    	String url = "http://i.baimao.com/user/center/checkcode";
    	System.out.println(post(url, "captcha=" + captcha));

    	String urlGetCode = "http://i.baimao.com/user/center/getcode";
    	System.out.println(post(urlGetCode, "phonenum=13881713500&type=1"));
    	System.out.println(JSON.parseObject("{\"errorcode\":3,\"errormsg\":\"\",\"data\":[]}").get("errorcode"));
    }
}